import random
from deap import base, creator, tools, algorithms
import evaluate
from constraint import Problem
def evaluate(individual):
    x, y = individual
    if x + y <= 10:  # 如果不满足约束条件，则给定非常低的适应度
        return 0,
    else:
        return x + y,  # 适应度是x + y的值
# 定义DEAP的个体类型
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)

# 初始化DEAP工具箱
toolbox = base.Toolbox()

# 属性（基因）初始化器
toolbox.register("attr_bool", random.randint, 0, 1)

# 个体初始化器
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, n=2)

# 种群初始化器
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

# 定义遗传算子
toolbox.register("evaluate", evaluate)  # 使用新的适应度函数
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)

# 新的适应度函数，要求x + y > 10


# ...

# 主程序
def main():
    random.seed(64)

    # 创建种群
    pop = toolbox.population(n=50)

    # CXPB  是交配概率
    # MUTPB 是突变概率
    CXPB, MUTPB = 0.5, 0.2

    # 适应度评估
    map_fits = list(map(toolbox.evaluate, pop))
    for fit, ind in zip(map_fits, pop):
        ind.fitness.values = fit

    # 进化
    pop, logbook = algorithms.eaSimple(pop, toolbox, cxpb=CXPB, mutpb=MUTPB, ngen=40,
                                       verbose=True)

    # 输出最优个体
    best_ind = tools.selBest(pop, 1)[0]
    print("Best individual is %s, %s" % (best_ind, best_ind.fitness.values))


if __name__ == "__main__":
    main()